package com.reggie.common.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 请求连接上下文
 *
 * @author yth
 * @since 2023-06-10-16:47
 */
public class CommonContext {

    private static final ThreadLocal<CommonContext> CONTEXT_HOLDER = ThreadLocal.withInitial(CommonContext::new);

    /**
     * 当前上下文的属性
     */
    private Map<Object, Object> properties = new HashMap<>(16);

    /**
     * @return 当前请求连接的上下文
     */
    public static CommonContext getContext() {
        return CONTEXT_HOLDER.get();
    }

    /**
     * @param key   key
     * @param value value
     */
    public void putProperty(Object key, Object value) {
        properties.put(key, value);
    }

    public Object getProperty(Object key) {
        return properties.get(key);
    }

    /**
     * 清除数据
     */
    public void removeAllProperties() {
        properties.clear();
    }

    /**
     * @return properties视图
     */
    public Map<Object, Object> getPropertiesView() {
        return new HashMap<>(properties);
    }

    /**
     * put all to properties
     */
    public void putAllProperties(Map<Object, Object> properties) {
        this.properties.putAll(properties);
    }

    private CommonContext() {
    }
}
